package com.hxx.day5.hxx;

import org.junit.Test;

import javax.management.RuntimeMBeanException;
import java.io.*;

public class TestDemo {
    public static void main(String[] args) {
        try {
            int i = 1;
            int n = 10;
            System.out.println(i/n);
            System.out.println("程序继续执行");
        } catch (ArithmeticException e) {
            e.printStackTrace();
            //System.out.println("除数不能为0");
            //System.out.println(e.getMessage());
        }
    }

    @Test
    public void test1() {
        try {
            InputStream is = new FileInputStream("d:/a.txt");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    @Test
    public void test2() {
        InputStream is = null;
        try {
            is = new FileInputStream("d:/a.txt");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 推荐
     */
    @Test
    public void test3() {
        //自动关闭流
        try(InputStream is = new FileInputStream("d:/a.txt");
            OutputStream out = new FileOutputStream("d:/b.txt");) {

        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void test4() {
       try {
           System.out.println(1/0);
       }catch (ArithmeticException  | NullPointerException e){
           e.printStackTrace();
       }finally {
           System.out.println("程序继续执行");
       }
    }
    @Test
    public void test5() {
        System.out.println(method1());
    }

    private static int method1() {
        int a = 10;
        try {
            return a;
        }finally {
            a = 100;
        }
    }

    /**
     * 使用异常声明
     */
    @Test
    public void test6() {
        try {
            //处理异常
            method2();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void method2()throws Exception{
        System.out.println("-----使用异常声明-----");
    }

    @Test
    public void test7() {
        method3();
    }
    /**
     * 运行期异常
     * 非受控异常
     */
    public void method3()throws RuntimeException {
        System.out.println("-----非受控异常-----");
    }

    /**
     * 自定义异常
     */
    @Test
    public void test8() {
        System.out.println(1/0);
        try {
            throw new MyException();
            //相当于return，以下的代码不能执行了
           // System.out.println();
        } catch (MyException e) {
            throw new RuntimeException("不能被0除");
        }
    }

    /**
     * 自定义运行期异常
     */
    @Test
    public void test9() {
        System.out.println(1/0);
        throw new MyRuntimeException();
    }
}





















